﻿Imports ISNet.WebUI.WebTreeView
Imports System.Data
Imports log4net

Partial Class Selector
    Inherits System.Web.UI.Page

    Dim sel_type As Integer = 0
    Public scripttext As String
    Private Shared logger As ILog = LogManager.GetLogger("Selector")

    Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
        WebCombo3.EncodeOutput = True
    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Add By Orn 15/07/2558 แก้ปัญหาเรื่อง เมื่อกดปุ่ม Back แล้ว fundcenter และ version ไม่ clear ค่า
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.Cache.SetExpires(DateTime.Now)
        Response.Cache.SetNoServerCaching()
        Response.Cache.SetNoStore()

        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If
        sel_type = Val(Request("type"))

        If IsPostBack = False Then
            Session.Remove("CMMT_OT_CODE")
            Session.Remove("CMMT_TR_CODE")
            Session.Remove("dfctr")
            Session.Remove("dfctrname")
            Try
                Dim adap As New DBdataTableAdapters.AppConfigsTableAdapter
                Dim dt As New DBdata.AppConfigsDataTable
                dt = adap.GetData
                For Each item As DBdata.AppConfigsRow In dt
                    Select Case item.Name
                        Case "ACTIVE_PLAN_YEAR"
                            YearTxt.Text = item.Value
                        Case "CMMT_OT_CODE"
                            Session.Add("CMMT_OT_CODE", item.Value)
                        Case "CMMT_TR_CODE"
                            Session.Add("CMMT_TR_CODE", item.Value)
                    End Select
                Next
            Catch ex As Exception
                logger.Error(ex.Message)
                logger.Error(ex.StackTrace)
            End Try

            'YearTxt.Text = "2556"
            VersionTxt.Text = "1"
            'PlotNode()
            'WebTreeView3.ExpandAll()

            If Val(Request("type")) = 45 Then
                VersionTxt.Text = "5"
            End If
        End If

        'Response.Write(GetSubFundCenter("0014"))
        'Response.Write(GetFromToFundCenter("1", "9", Session("users")))
    End Sub

    Protected Sub WebCombo3_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo3.InitializeDataSource
        Dim adap As New FundCenterParentTableAdapters.SelectorTableAdapter
        Dim dt As New FundCenterParent.SelectorDataTable
        Dim dt2 As New FundCenterParent.SelectorDataTable
        Dim sql = ""
        'Dim prefil As String = ""
        'prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FctH.PlanYear = " & Val(Session("PlanYear"))
        'If prefil <> "" Then
        '    sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        'End If
        sql += "ORDER BY Grouppath"
        adap.GetDataByFilter(dt2, sql)
        dt.Rows.Add("ทุกรายการ", "0", 0, "0", Val(Session("PlanYear")), "ทุกรายการ")
        dt.Merge(dt2)
        'dt.DefaultView.Sort = "FundCenter_FundCenterCode"
        e.DataSource = dt

        If dt.Count = 2 Then
            WebCombo3.Value = dt.Item(1).FundCenter_FundCenterCode

            Session.Add("dfctr", dt.Item(1).FundCenter_FundCenterCode)
            Session.Add("dfctrname", dt.Item(1).Description)
        Else
            WebCombo3.Value = dt.Item(0).FundCenter_FundCenterCode
        End If

    End Sub

    Sub PlotNode()

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()

        Dim adapter As New FundCenterParentTableAdapters.fctr_viewTableAdapter
        Dim dt As New FundCenterParent.fctr_viewDataTable
        dt = adapter.GetDataByUser(Session("users"), Val(YearTxt.Text))

        Dim root_id As String
        If dt.Count = 1 Then
            For Each row As FundCenterParent.fctr_viewRow In dt
                MyNode.Text = row.description
                MyNode.Value = row.FundCenterCode
                root_id = row.FundCenterCode
                FCTRcode.Text = row.FundCenterCode
                FCTRName.Text = row.description
            Next
            WebCombo3.Visible = False
            WebTreeView3.Visible = False
            FCTRName.Visible = True
            CheckBox1.Visible = False
            Exit Sub
        Else
            WebCombo3.Visible = True
            WebTreeView3.Visible = True
            FCTRName.Visible = False
            CheckBox1.Visible = True

            MyNode.Text = "GSB"
            MyNode.Value = "0"
            root_id = "0"

        End If

        If dt.Count > 0 Then
            Dim rootpath = ""
            rootpath = FctrClass.GetRoot(Session("users"), Val(YearTxt.Text))
            Dim rootarr() As String = Split(rootpath, ",")
            WebTreeView3.Nodes.Add(MyNode)

            For i = 0 To rootarr.Length - 1
                PlotChild(rootarr(i), MyNode, 1)
            Next
        End If
    End Sub

    Sub PlotChild(ByVal gpath As String, ByRef cnode As WebTreeViewNode, ByVal level As Decimal)
        'Response.Write(gpath & "<br />")
        Dim Hadapter As New FundCenterParentTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterParent.FctHDataTable
        Hdatatable = Hadapter.GetDataByGPath(gpath, Val(Session("PlanYear")))

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()
        For Each row As FundCenterParent.FctHRow In Hdatatable


            MyNode.Text = row.Description
            MyNode.Value = row.FundCenter_FundCenterCode

            cnode.Nodes.Add(MyNode)
        Next
        'Hdatatable = Hadapter.GetDataByUserLikeGpath(gpath & "__", Session("users"), Val(Session("PlanYear")))
        If Len(gpath) >= 10 Then
            Exit Sub
        End If
        Dim pathadd As String = "__"
        'For i = 1 To 4
        '    Dim fullpath As String = gpath & pathadd
        '    Hdatatable = Hadapter.GetDataByUserLikeGpath(fullpath, Session("users"), Val(Session("PlanYear")))
        '    If Hdatatable.Count > 0 Then
        '        Exit For
        '    End If
        '    'Response.Write(fullpath & "<br />")
        '    pathadd += "__"
        'Next
        'Response.Write(Hdatatable.Count)
        Dim fullpath As String = gpath & pathadd
        Hdatatable = Hadapter.GetDataByUserLikeGpath(fullpath, Session("users"), Val(Session("PlanYear")))
        For Each row As FundCenterParent.FctHRow In Hdatatable
            If Len(row.grouppath) <= 10 Then
                PlotChild(row.grouppath, MyNode, level + 1)
            End If
        Next
    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        WebTreeView3.Dispose()
        Dim org_level As String = "10"
        Dim adapter As New FundCenterParentTableAdapters.FundCenterHierarchiesTableAdapter
        Try
            org_level = adapter.GetMaxOrglevel(Session("users"))
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        Dim closeVersion As Integer = 0
        Dim adapBudgetVersion As New MasterDataSetTableAdapters.BudgetVersionsTableAdapter
        closeVersion = adapBudgetVersion.CheckCloseVersion(Session("PlanYear"), VersionTxt.Text)
        If closeVersion > 0 Then
            scripttext = "<script>alert('Version " & VersionTxt.Text & " ไม่อนุญาตให้บันทึกรายการ');</script>"
            'PlotNode()
            Exit Sub
        End If


        Dim userlvl As Integer = 1
        userlvl = FctrClass.GetLevelFromOrg(org_level)
        If userlvl < Val(VersionTxt.Text) And Not (userlvl = 5 Or (Session("RoleType") = 1 Or Session("RoleType") = 5)) Then
            scripttext = "<script>alert('ไม่มีสิทธิใน Version " & VersionTxt.Text & " ');</script>"
            'PlotNode()
            Exit Sub
        ElseIf Val(Left(VersionTxt.Text, 1)) = 0 And Not (userlvl = 5 Or (Session("RoleType") = 1 Or Session("RoleType") = 5)) Then
            scripttext = "<script>alert('ไม่มีสิทธิใน Version " & VersionTxt.Text & " ');</script>"
            'PlotNode()
            Exit Sub
        End If
        Dim fctr_val As String = ""
        If FCTRName.Visible = True Then
            fctr_val = FCTRcode.Text
        Else
            fctr_val = WebCombo3.Value
        End If
        If Val(Session("RoleType")) <> 5 And Val(Session("RoleType")) <> 1 Then
            If VersionTxt.Text.Trim = "1" Or VersionTxt.Text.Trim = "2" Or VersionTxt.Text.Trim = "3" Or VersionTxt.Text.Trim = "4" Or VersionTxt.Text.Trim = "5" Then
                Dim adap2 As New checkPlanDSTableAdapters.FundCenterReleasesTableAdapter
                Dim exist As Integer = 0
                If Val(fctr_val) <> 0 Then
                    exist = adap2.checkExist(fctr_val.Trim, Val(YearTxt.Text), VersionTxt.Text)
                Else
                    exist = adap2.CheckExistAll(Val(YearTxt.Text), VersionTxt.Text)
                End If

                If exist = 0 And VersionTxt.Text.Trim <> "1" Then
                    scripttext = "<script>alert('คุณยังไม่ได้ Copy Version " & VersionTxt.Text & " ');</script>"
                    PlotNode()
                    Exit Sub
                End If
            End If
        End If

        If fctr_val.Trim <> "" Then
            Session.Remove("prefilter")
            If CheckBox1.Checked = True Then
                Session.Add("prefilter", FctrClass.GetSubFundCenter(fctr_val, Session("users"), Val(YearTxt.Text), ""))
                'Response.Write(FctrClass.GetSubFundCenter(fctr_val, Session("users"), Val(YearTxt.Text), ""))
                'Exit Sub
            Else
                'Response.Write(fctr_val)
                'Exit Sub
                Session.Add("prefilter", "'" & fctr_val & "'")
            End If

            Session.Remove("PlanYear")
            Session.Add("PlanYear", Val(YearTxt.Text))
            Session.Remove("FCTR")
            Session.Add("FCTR", fctr_val)
            Session.Remove("Versions")
            Session.Add("Versions", VersionTxt.Text)
            'Response.Write(Session("prefilter"))
            'Exit Sub

            If CheckBox1.Checked = False And FCTRName.Visible = False Then
                Session.Remove("dfctr")
                Session.Remove("dfctrname")
                Session.Add("dfctr", fctr_val)
                Session.Add("dfctrname", WebCombo3.SelectedRow.Cells(1).Value)
            End If

            If CheckBox1.Checked = True Then
                Dim sql = FctrClass.GetSubFundCenter(fctr_val, Session("users"), Val(YearTxt.Text), "")
                Dim fcadap As New FundCenterParentTableAdapters.FctHSelectorTableAdapter
                Dim fcdt As New FundCenterParent.FctHSelectorDataTable
                fcadap.GetDataByFilter(fcdt, sql)
                If fcdt.Count = 1 Then
                    Session.Remove("dfctr")
                    Session.Remove("dfctrname")
                    Session.Add("dfctr", fcdt.Item(0).FundCenter_FundCenterCode)
                    Dim fc2adap As New FundCenter2TableAdapters.FundCentersTableAdapter
                    Session.Add("dfctrname", fc2adap.GetName(fcdt.Item(0).FundCenter_FundCenterCode, Val(YearTxt.Text)))
                End If
            End If

            If sel_type = 1 Then
                Response.Redirect("BudgetProject.aspx" & "?ptype=" & Request("ptype"))
            ElseIf sel_type = 2 Then
                Response.Redirect("OTUsual.aspx")
            ElseIf sel_type = 3 Then
                Response.Redirect("TravelProject.aspx" & "?ptype=" & Request("ptype"))
            ElseIf sel_type = 4 Then
                Response.Redirect("TravelUsual.aspx")
            ElseIf sel_type = 5 Then
                Response.Redirect("OtherProject.aspx" & "?ptype=" & Request("ptype"))
            ElseIf sel_type = 6 Then
                Response.Redirect("OtherUsual.aspx")
            ElseIf sel_type = 7 Then
                Response.Redirect("ActTypeProject.aspx" & "?ptype=" & Request("ptype"))
            ElseIf sel_type = 8 Then
                Response.Redirect("ActTypeUsual.aspx")
            ElseIf sel_type = 10 Then
                Response.Redirect("F05.aspx")
            ElseIf sel_type = 12 Then
                Response.Redirect("Sinchuatobtan.aspx")
            ElseIf sel_type = 14 Then
                Response.Redirect("SinchuaBudgetForm.aspx")
            ElseIf sel_type = 16 Then
                Response.Redirect("LifeCheckForm.aspx")
            ElseIf sel_type = 18 Then
                Response.Redirect("CreditLifeAssureForm.aspx")
            ElseIf sel_type = 20 Then
                Response.Redirect("GPResponseForm.aspx")
            ElseIf sel_type = 30 Then
                Response.Redirect("ShareMonthFormProject.aspx")
            ElseIf sel_type = 41 Then
                Response.Redirect("P01.aspx")
            ElseIf sel_type = 42 Then
                Response.Redirect("P02.aspx")
            ElseIf sel_type = 43 Then
                Response.Redirect("NPLTarget.aspx")
            ElseIf sel_type = 44 Then
                Response.Redirect("ResponseTarget.aspx")
            ElseIf sel_type = 45 Then
                If VersionTxt.Text = "1" Or VersionTxt.Text = "2" Or VersionTxt.Text = "3" Or VersionTxt.Text = "4" Then
                    scripttext = "<script>alert('ฟอร์ม Review วงเงินงบประมาณ ออกแบบให้ฝบป. ใช้ในการวิเคราะห์ข้อมูลงบประมาณแบบไม่ลงรายละเอียดเท่านั้น');</script>"
                    PlotNode()
                    Exit Sub
                End If

                Response.Redirect("B03_CheckBudgetLimit.aspx")
            ElseIf sel_type = 46 Then
                If VersionTxt.Text = "1" Or VersionTxt.Text = "2" Or VersionTxt.Text = "3" Or VersionTxt.Text = "4" Or VersionTxt.Text = "5" Then
                    scripttext = "<script>alert('ฟอร์มกำหนดกรอบวงเงินงบประมาณไม่สามารถใช้ได้กับ Version ปกติ');</script>"
                    PlotNode()
                    Exit Sub
                End If

                Response.Redirect("B05_FixMoneyLimit.aspx")
            ElseIf sel_type = 56 Then
                Response.Redirect("B06FPrgPD.aspx")
            ElseIf sel_type = 57 Then
                Response.Redirect("FundedProgramRegen.aspx")
            Else
                Response.Redirect("Default.aspx")
            End If
        Else
            PlotNode()
        End If
    End Sub

    Dim fctr As String = ""
    Function GetFromToFundCenter(ByVal fromfctr As String, ByVal tofctr As String, ByVal users As String) As String
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        dt = adap.GetDataByFromTo(fromfctr, tofctr, users, Val(YearTxt.Text))

        Dim result As String = "0"

        For Each row As BasicData.FCTR_Child2Row In dt
            result += "," & row.FundCenterCode
        Next

        Return result
    End Function

    Function GetSubFundCenter(ByVal fctr_code As String) As String
        Dim result As String

        result = fctr_code
        GetChild(fctr_code, result) '0 ตัวแรก id ตัว root

        Return result
    End Function

    Sub GetChild(ByVal parent_id As String, ByRef result As String)
        Dim showdata As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim showd As BasicData.FCTR_Child2DataTable
        showd = showdata.GetChild(parent_id, Session("users"), Val(YearTxt.Text))

        For Each shownameRow As BasicData.FCTR_Child2Row In showd
            result += "," & shownameRow.FundCenterCode
            GetChild(shownameRow.FundCenterCode, result)
        Next
    End Sub
End Class
